package com.bigdata.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;


@Configuration
public class RabbitConfig {

    @Bean
    public Queue queue(){
        HashMap<String, Object> props = new HashMap<>();
        // 存活时间 5s
        props.put("x-message-ttl", 5000);
        // 设置该队列所关联的死信交换器（当队列消息TTL到期后依然没有消费，则加入死信队列）
        props.put("x-dead-letter-exchange", "exchange.order.dlx");
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原队列的routingKey
        props.put("x-dead-letter-routing-key", "order.dlx");

        Queue queue = new Queue("queue.order",true,false,false);
        return queue;
    }

    // 定义交换器
    @Bean
    public Exchange exchange() {
        DirectExchange exchange = new DirectExchange("exchange.order", true,
                false, null);
        return exchange;
    }

    // 绑定队列与交换器
    @Bean
    public Binding binding(){

        Binding binding = BindingBuilder.bind(queue()).to(exchange()).with("order").noargs();
        return binding;
    }

    // 死信队列
    @Bean
    public Queue queueDlx() {
        Queue queue = new Queue("queue.order.dlx", true, false, false);
        return queue;
    }

    /**
     * 死信交换器
     * @return
     */
    @Bean
    public Exchange exchangeDlx() {
        DirectExchange exchange = new DirectExchange("exchange.order.dlx", true,
                false, null);
        return exchange;
    }

    @Bean
    public Binding bindingDlx(){
        Binding bindingDlx = BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with("order.dlx").noargs();
        return bindingDlx;
    }

}
